package com.chub.study.modules.controller;


import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chub.RespResult;
import com.chub.study.modules.annotation.DictTranslate;
import com.chub.study.modules.annotation.LogRecord;
import com.chub.study.modules.constants.enums.TMessageEnum;
import com.chub.study.modules.dto.StudInfoDTO;
import com.chub.study.modules.entity.TAddrInfo;
import com.chub.study.modules.entity.TClassInfo;
import com.chub.study.modules.entity.TMessage;
import com.chub.study.modules.entity.TStudInfo;
import com.chub.study.modules.mapper.TAddrInfoMapper;
import com.chub.study.modules.mapper.TClassInfoMapper;
import com.chub.study.modules.mapper.TStudInfoMapper;
import com.chub.study.modules.service.TLogService;
import com.chub.study.modules.service.TMessageService;
import com.chub.study.modules.service.TStudInfoService;
import com.chub.study.util.Constants;
import com.chub.study.util.SmartWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生信息表 前端控制器
 * </p>
 *
 * @author chub
 * @since 2021-08-26
 */
@RestController
@Api(tags = "学生信息的服务")
@RequestMapping("/modules/tstudinfo")
public class TStudInfoController extends BaseController {

    @Resource
    private TStudInfoMapper studInfoMapper;

    @Resource
    private TAddrInfoMapper addrInfoMapper;

    @Resource
    private TClassInfoMapper classInfoMapper;

    @Resource
    private TStudInfoService studInfoService;

    @Resource
    private TMessageService messageService;

    @Resource
    private TLogService logService;

    @ApiOperation(value = "查询学生信息列表。")
    @PostMapping("/selectStudListByPage")
    @DictTranslate
    public RespResult<IPage> selectStudListByPage(@RequestBody StudInfoDTO reqDto) {

        logger.info("要查询的学生信息 = {}", reqDto);
        logger.info("fastjson接收信息为 --> {}", JSON.toJSONString(reqDto));
//        logger.info("hutooljson接收信息为 --> {}", JSON.toJSONString(studInfo));
//        cn.hutool.json.JSONUtil.toJsonStr();
//        String jsons = "{'com':'zhongtong','data':[{'ftime':'2019-05-15 13:43:51','context':'【上海市】 快件已在 【九亭三部】 签收'},{'ftime':'2019-05-14 13:43:51','context':'【上海市】 快件已在 【九亭三部】 签收'}]}";
//        JSONObject json = new JSONObject(jsons);


        return RespResult.success(studInfoService.selectStudListByPage(reqDto));


        //
        // List<TStudInfo> respList;
        // if (reqDto != null) {
        //     QueryWrapper<TStudInfo> queryWrapper = new QueryWrapper<>();
        //     queryWrapper.eq(StrUtil.isNotEmpty(reqDto.getBjbh()), "BJBH", reqDto.getBjbh());
        //     queryWrapper.like(StrUtil.isNotEmpty(reqDto.getXsxm()), "XSXM", reqDto.getXsxm());
        //
        //
        //     // respList = studInfoMapper.selectList(queryWrapper);
        //     respList = studInfoService.list(queryWrapper);
        // } else {
        //     respList = studInfoService.list();
        // }
        //
        // if (IterUtil.isEmpty(respList)) {
        //     return RespResult.success(respList);
        // }
        //
        // for (TStudInfo tmp: respList) {
        //     if (StrUtil.isEmpty(tmp.getXsbh())){
        //         continue;
        //     }
        //     List<TAddrInfo> list1;
        //     QueryWrapper<TAddrInfo> queryWrapper1 = new QueryWrapper<>();
        //     queryWrapper1.eq("ADDR_BLNG_ID", tmp.getXsbh());
        //     list1 = addrInfoMapper.selectList(queryWrapper1);
        //     tmp.setAddrList(list1);
        // }
        //
        //
        // return RespResult.success(respList);
    }


    @ApiOperation(value = "查询学生信息列表。")
    @PostMapping("/getStudList")
    @DictTranslate
    public RespResult<List<TStudInfo>> getStudList(@RequestBody StudInfoDTO reqDto) {

        logger.info("要查询的学生信息 = {}", reqDto);
        logger.info("fastjson接收信息为 --> {}", JSON.toJSONString(reqDto));
//        logger.info("hutooljson接收信息为 --> {}", JSON.toJSONString(studInfo));
//        cn.hutool.json.JSONUtil.toJsonStr();
//        String jsons = "{'com':'zhongtong','data':[{'ftime':'2019-05-15 13:43:51','context':'【上海市】 快件已在 【九亭三部】 签收'},{'ftime':'2019-05-14 13:43:51','context':'【上海市】 快件已在 【九亭三部】 签收'}]}";
//        JSONObject json = new JSONObject(jsons);

        List<TStudInfo> respList;
        if (reqDto != null) {
            QueryWrapper<TStudInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StrUtil.isNotEmpty(reqDto.getBjbh()), "BJBH", reqDto.getBjbh());
            queryWrapper.like(StrUtil.isNotEmpty(reqDto.getXsxm()), "XSXM", reqDto.getXsxm());

            // respList = studInfoMapper.selectList(queryWrapper);
            respList = studInfoService.list(queryWrapper);
        } else {
            respList = studInfoService.list();
        }

        if (IterUtil.isEmpty(respList)) {
            return RespResult.success(respList);
        }

        for (TStudInfo tmp : respList) {
            if (StrUtil.isEmpty(tmp.getXsbh())) {
                continue;
            }
            // List<TAddrInfo> list1;
            // QueryWrapper<TAddrInfo> queryWrapper1 = new QueryWrapper<>();
            // queryWrapper1.eq("ADDR_ID", tmp.getXsbh());
            // list1 = addrInfoMapper.selectList(queryWrapper1);
            // tmp.setAddrList(list1);
            logger.info("查询学生信息列表， 学生编号:{}", tmp.getXsbh());
            tmp.setHomeAddrBean(addrInfoMapper.selectById(tmp.getXsbh()));
        }


        return RespResult.success(respList);
    }

    @LogRecord(methodDesc = "查询学生、地址信息列表")
    @ApiOperation(value = "查询学生、地址信息列表")
    @PostMapping("/selectStudAndAddrList")
    @DictTranslate
    public RespResult<List<TStudInfo>> selectStudAndAddrList(@RequestBody StudInfoDTO reqDto) {


        logger.info("要查询的学生信息 = {}", reqDto);
        logger.info("fastjson接收信息为 --> {}", JSON.toJSONString(reqDto));
//        logger.info("hutooljson接收信息为 --> {}", JSON.toJSONString(studInfo));
//        cn.hutool.json.JSONUtil.toJsonStr();
//        String jsons = "{'com':'zhongtong','data':[{'ftime':'2019-05-15 13:43:51','context':'【上海市】 快件已在 【九亭三部】 签收'},{'ftime':'2019-05-14 13:43:51','context':'【上海市】 快件已在 【九亭三部】 签收'}]}";
//        JSONObject json = new JSONObject(jsons);

        List<TStudInfo> respList;

        respList = studInfoMapper.selectStudAndAddrList(reqDto);


        // if (IterUtil.isEmpty(respList)) {
        //     return RespResult.success(respList);
        // }


        return RespResult.success(respList);
    }


    @ApiOperation(value = "查询学生、地址信息列表")
    @GetMapping("/selectStudAndAddrList1")
    public RespResult<String> selectStudAndAddrList1(@RequestParam String bjbh, @RequestParam String xsxm, @RequestParam String xsbh, @RequestParam String phone) {

        // 记录用户信息到日志
        logger.info("333User Info - bjbh: {}, xsxm: {}", bjbh, xsxm);

        // 这里调用logger.info()方法，会打印出日志信息，但是不会打印出用户信息，xsbh、phone传不过来，TODO:这是为什么
        logger.info("333User Info - ID Card: {}, Phone Number: {}", xsbh, phone);

        // 这里调用logger.info()方法，会打印出日志信息，并且会打印出用户信息
        logger.info(StrUtil.format("User Info - ID Card: {}, Phone Number: {}", xsbh, phone));


        return RespResult.success("User info logged");

        // logger.info("要查询的学生信息 = {}", reqDto);
        // logger.info("fastjson接收信息为 --> {}", JSON.toJSONString(reqDto));
        //
        // List<TStudInfo> respList;
        // respList = studInfoMapper.selectStudAndAddrList(reqDto);
        // return RespResult.success(respList);
    }

    @ApiOperation(value = "查询学生信息列表。")
    @PostMapping("/getStudListByMap")
    public RespResult<List<TStudInfo>> getStudListByMap(@RequestBody Map<String, String> reqMap) {

        logger.info("要查询的学生信息 = {}", reqMap);
        logger.info("fastjson接收信息为 --> {}", JSON.toJSONString(reqMap));

        // 这样  DictTranslateAop 可以将字典翻译成功
        return RespResult.success(studInfoService.getStudListByMap(reqMap));

        // 这样 @DictName(type = "SEX_TYPE", filedName = "xsxb", valSeparator = "|", nameSeparator = "+")  注解不起作用???
        // List<TStudInfo> list = null;
        // if (reqMap != null) {
        //     QueryWrapper<TStudInfo> queryWrapper = new QueryWrapper<>();
        //     queryWrapper.eq(StrUtil.isNotEmpty(reqMap.get("bjbh")), "BJBH", reqMap.get("bjbh"));
        //     queryWrapper.like(StrUtil.isNotEmpty(reqMap.get("xsxm")), "XSXM", reqMap.get("xsxm"));
        //     list = studInfoMapper.selectList(queryWrapper);
        // } else {
        //     list = studInfoMapper.selectList(null);
        // }
        // return list;
    }


    @ApiOperation("创建")
    @PostMapping("/create")
    public RespResult create(@Valid @RequestBody TMessage reqMsg) {
        logger.info("请求参数-->{}", JSONObject.toJSONString(reqMsg));

        TMessage message = messageService.saveReqMessage(reqMsg);

        TStudInfo tStudInfo = reqMsg.getMsgBody().toJavaObject(TStudInfo.class);

        StringBuilder stringBuilder = new StringBuilder();
        if (ObjectUtil.isEmpty(tStudInfo)) {
            stringBuilder.append(Constants.REQ_PARAM_CANNOT_BE_EMPTY);
        }

        if (StrUtil.isBlank(tStudInfo.getXsbh())) {
            stringBuilder.append(Constants.StudentConstants.XSBH_CANNOT_BE_EMPTY);
        }

        String bjbh = tStudInfo.getBjbh();
        if (StrUtil.isBlank(tStudInfo.getBjbh())) {
            stringBuilder.append(Constants.StudentConstants.BJBH_CANNOT_BE_EMPTY);
        }

        QueryWrapper<TClassInfo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("BJBH", bjbh);
        TClassInfo classInfo = classInfoMapper.selectOne(queryWrapper);
        if (classInfo == null) {
            String info = StrUtil.format(Constants.StudentConstants.BJBH_NON_EXISTENT, bjbh);
            stringBuilder.append(info);
        }

        logger.info("请求参数验证本该打印日志的的这里不打印日志了，记到数据库里。");
        // 准备将请求参数错误信息返回给请求方
        String respInfo = stringBuilder.toString();
        // 如果校验请求参数又错误，需要记录日志，更新报文处理状态，将错误信息返回给请求方
        if (!respInfo.isEmpty()) {
            logger.info("请求参数-->{}", JSONObject.toJSONString(respInfo));
            // logService.saveHandleLog(message, TLogEnum.LOG_LEVEL_INFO.getCode(), TMessageEnum.INVAILD_MESSAGE.getCode(), returnInfo);
            logService.info(message, TMessageEnum.INVAILD_MESSAGE.getCode(), respInfo);
            return RespResult.error(respInfo);
        }

        boolean saveFlag = false;

        try {
            // tStudInfo.getAddrList().forEach(addrInfoMapper::insert);

            tStudInfo.getAddrList().stream().peek(item -> {
                item.setCrtUserCode("System");   // 这里可以对字段值做处理
                item.setModUserCode("System");
                // item.getCityList().forEach(cityInfoMapper::insert);  // 对于嵌套的List可以在这里继续处理
            }).forEach(addrInfoMapper::insert);


            saveFlag = studInfoService.save(tStudInfo);

        } catch (Exception e) {
            logger.error("数据处理异常本该打印日志的的这里不打印日志了，记到数据库里。");
            // logService.saveHandleLog(message, TLogEnum.LOG_LEVEL_ERROR.getCode(),  TMessageEnum.HANDLE_FIAL.getCode(), e.toString());
            logService.error(message, TMessageEnum.HANDLE_FIAL.getCode(), e.toString());
            return RespResult.error(Constants.REQ_HANDLE_FAIL);
        }
        logger.info("数据处理完成本该打印日志的的这里不打印日志了，记到数据库里。");
        // logService.saveHandleLog(message, TLogEnum.LOG_LEVEL_INFO.getCode(), TMessageEnum.HANDLE_SUCC.getCode(), Constants.REQ_HANDLE_SUCC);
        logService.info(message, TMessageEnum.HANDLE_SUCC.getCode(), Constants.REQ_HANDLE_SUCC);
        return RespResult.success(tStudInfo);
    }

    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public RespResult<String> delete(@RequestParam String id) {
        studInfoService.removeById(id);
        return RespResult.success();
    }

    @ApiOperation(value = "修改")
    @PostMapping("/modify")
    public RespResult<String> modify(@Valid @RequestBody TStudInfo tStudInfo) {
        studInfoService.updateById(tStudInfo);
        return RespResult.success();
    }

    @ApiOperation(value = "查询详情")
    @GetMapping("/detail")
    public RespResult<TStudInfo> detail(@RequestParam String id) {
        return RespResult.success(studInfoService.getById(id));
    }

    @ApiOperation(value = "分页查询")
    @PostMapping("/queryByPage")
    public RespResult<IPage<TStudInfo>> queryByPage(@RequestBody JSONObject queryObject) {

        SmartWrapper<TStudInfo> smartWrapper = new SmartWrapper<>();
        smartWrapper.parse(queryObject, TStudInfo.class);

        QueryWrapper<TStudInfo> queryWrapper = smartWrapper.getQueryWrapper();
        IPage<TStudInfo> page = smartWrapper.generatePage();
        studInfoService.page(page, queryWrapper);
        return RespResult.success(page);
    }


    @ApiOperation(value = "查询学生信息列表。")
    @PostMapping("/getStudListByProcedure")
    public RespResult<List<TStudInfo>> getStudListByProcedure(@RequestBody TStudInfo studInfo) {
        logger.info("要查询的学生信息 = {}", studInfo);
        logger.info("fastjson接收信息为 --> {}", JSON.toJSONString(studInfo));

        return RespResult.success(studInfoService.getStudListByProcedure(studInfo.getBjbh()));
    }

    @ApiOperation(value = "查询学生信息列表。")
    @PostMapping("/getStudListMapByProcedure")
    public RespResult<List<Map<String, Object>>> getStudListMapByProcedure(@RequestBody TStudInfo studInfo) {
        logger.info("要查询的学生信息 = {}", studInfo);
        logger.info("fastjson接收信息为 --> {}", JSON.toJSONString(studInfo));

        return RespResult.success(studInfoService.getStudListMapByProcedure(studInfo.getBjbh()));
    }

    /**
     * @param : reqJson
     * @return : RespResult<Integer>
     * @description : TODO
     * @author : chub
     * @date : 2024-03-28 16:28
     */
    @ApiOperation(value = "批量插入学生信息。")
    @PostMapping("/batchInsert")
    public RespResult<Integer> batchInsert(@RequestBody JSONObject reqJson) {

        logger.info("要插入的学生信息总数量为10000，每批次500条，耗时最少，耗时1.37s，可以根据运行环境多次测试确定每批次数量。");
        int totalCnt = reqJson.getIntValue("totalCnt");
        int batchNum = reqJson.getIntValue("batchNum");
        logger.info("要插入的学生信息数量 = {}", totalCnt);
        logger.info("要插入的学生信息每批记录数量 = {}", reqJson.getIntValue("batchNum"));


        return RespResult.success(studInfoService.batchInsert(totalCnt, batchNum));
    }


}

